<?php

namespace app\admin\controller\apply;

use app\admin\model\ProjectFeeitem;
use app\common\model\Project;
use app\common\service\workflow\WFCreate;
use app\common\service\workflow\Workflow;
use think\db\exception\PDOException;
use Throwable;
use app\common\controller\Backend;

/**
 * 付款申请
 */
class Payment extends Backend
{
    /**
     * Payment模型对象
     * @var object
     * @phpstan-var \app\common\model\apply\Payment
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id'];

    protected array $withJoinTable = ['project', 'supplier', 'feeitem'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\common\model\apply\Payment;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $where[] = ['user_id', '=', $this->auth->id];
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['project' => ['title'], 'supplier' => ['company_name']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $project = \app\common\model\Project::findOrEmpty($data['project_id']);
            if($project->isEmpty() || $project->state != 1){
                $this->error('该项目已关闭或已删除！');
            }
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $data['user_id'] = $this->auth->id;
            $data['user_name'] = $this->auth->nickname;
            $feeitems = $data['feeitems'];
            $data['feeitems'] = json_encode($data['feeitems']);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $detail = $this->model->with(['project','feeitem', 'supplier'])->where([
                    ['id', '=', $this->model->id]
                ])->find()->toArray();
                $project = Project::find($data['project_id']);

                $admin = $this->auth->getAdmin()->toArray();
                $WFCreate = new WFCreate($admin);
                $WF = $WFCreate->create_flow(300, $detail, $project['title'].' 付款申请 ', $this->model->no);
                $Workflow = new Workflow($WF['flow_no'], $admin);
                $Workflow->start();

                foreach($feeitems as $v){
                    $projectFeeitem = ProjectFeeitem::where([
                        'project_id' => $data['project_id'],
                        'feeitem_id' => $v['feeitem_id'],
                    ])->findOrEmpty();
                    if(!$projectFeeitem->isEmpty()){
                        $projectFeeitem->calculate += $v['amount'];
                        $projectFeeitem->save();
                    }
                }

                $this->model->audit_state = 1;
                $this->model->wokerflow_id = $WF['id'];
                $this->model->save();
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage(), ["line" => $e->getLine(), "file" => $e->getFile()]);
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function paid(): void {
        $no = $this->request->post('no');
        $model = $this->model->where(['no'=> $no, 'audit_state' => 2])->findOrEmpty();
        if($model->isEmpty()){
            $this->error('未找到对应的申请！');
        }
        try {
            $model->paid = 1;
            $model->save();
            $this->success('操作成功！');
        } catch (PDOException $e){
            $this->error('操作失败！');
        }
    }
}